<!-- 优惠券管理 -->
<template>
   <div>
      <!-- 搜索添加导出 -->
      <div>
         <el-input size="" class="input-length" placeholder="请输入优惠券名称" v-model="list.title" />
         <el-select placeholder="请输入优惠券类型" style="width: 200px;margin-right: 10px;" v-model="list.type">
            <el-option label="满减券" value="1" />
            <el-option label="立减券" value="2" />
            <el-option label="全部" value="" />
         </el-select>
         <el-select placeholder="请选择优惠券状态" style="width: 200px;margin-right: 10px;" v-model="list.status">
            <el-option v-for="item in couponstatusMap" :value="item.value" :label="item.name" />
         </el-select>
         <el-button type="primary" :icon="Search" @click="handleSearch">查找</el-button>
         <el-button type="primary" :icon="Plus" @click="add">添加</el-button>
         <el-button type="primary" :icon="Bottom" @click="exports">当前页导出</el-button>
      </div>
      <!-- 创建弹窗 -->
      <el-dialog v-model="dialogFormVisible" title="创建" width='40%' destroy-on-close>
         <el-form :model="form.data" :rules="rules" ref="ruleFormRef" :disabled="bool">
            <el-form-item label="优惠券名称" :label-width="formLabelWidth" prop="title">
               <el-input v-model="form.data.title" autocomplete="off" />
            </el-form-item>
            <el-form-item label="优惠券类型" prop="type" :label-width="formLabelWidth">
               <el-select placeholder="" style="width: 240px" v-model="form.data.type">
                  <el-option label="满减券" :value="1" />
                  <el-option label="立减券" :value="2" />
               </el-select>
            </el-form-item>
            <el-form-item label="介绍" :label-width="formLabelWidth" prop="description">
               <el-input v-model="form.data.description" autocomplete="off" />
            </el-form-item>
            <el-form-item label="优惠券数量" :label-width="formLabelWidth" prop="total">
               <el-input v-model="form.data.total" placeholder="">
                  <template #append>张</template>
               </el-input>
            </el-form-item>
            <el-form-item label="每人限领" :label-width="formLabelWidth" prop="limit">
               <el-input v-model="form.data.limit" placeholder="">
                  <template #append>张</template>
               </el-input>
            </el-form-item>
            <el-form-item label="优惠金额" :label-width="formLabelWidth" prop="discount">
               <el-input v-model.number="form.data.discount" placeholder="">
                  <template #append>元</template>
               </el-input>
            </el-form-item>
            <el-form-item label="最低消费" :label-width="formLabelWidth" prop="min">
               <el-input v-model="form.data.min" placeholder="">
                  <template #append>张</template>
               </el-input>
            </el-form-item>
            <el-form-item label="优惠券状态" prop="status" :label-width="formLabelWidth">
               <el-select placeholder="请输入角色名称" style="width: 240px" v-model="form.data.status">
                  <el-option label="正常" :value="1" />
                  <el-option label="下架" :value="0" />
               </el-select>
            </el-form-item>
            <el-form-item label="有效期" :label-width="formLabelWidth">
               <el-radio-group v-model="form.data.timeType" size="large">
                  <el-radio-button :label='1'>领券相对天数</el-radio-button>
                  <el-radio-button :label='0'>指定绝对天数</el-radio-button>
               </el-radio-group>
            </el-form-item>
            <el-form-item label="" :label-width="formLabelWidth" v-if="form.data.timeType">
               <el-input v-model.number="form.data.days" placeholder="">
                  <template #append>天</template>
               </el-input>
            </el-form-item>
            <el-form-item label="" :label-width="formLabelWidth" v-else>
               <el-date-picker v-model="form.data.gmtStart" type="datetime" placeholder="选择日期" value-format="x" />至
               <el-date-picker v-model="form.data.gmtEnd" type="datetime" placeholder="选择日期" value-format="x" />
            </el-form-item>
            <el-form-item label="商品限制范围" :label-width="formLabelWidth">
               <el-radio-group v-model="form.data.goodsType" size="large">
                  <el-radio-button :label='0'>全场通用</el-radio-button>
                  <el-radio-button :label='1'>指定分类</el-radio-button>
               </el-radio-group>
            </el-form-item>
            <el-form-item label="优惠类目" :label-width="formLabelWidth" v-if="form.data.goodsType">
               <el-cascader v-model="form.data.categoryId" :options="options" :props="{
   checkStrictly: true, label: 'title', children: 'childrenList', value: 'id', emitPath: false
}" clearable />
               <el-form-item label="" :label-width="formLabelWidth">
               </el-form-item>
            </el-form-item>
         </el-form>
         <template #footer>
            <span class="dialog-footer">
               <el-button @click="dialogFormVisible = false">取消</el-button>
               <el-button type="primary" @click="handleToggleConfirm(ruleFormRef)">确定</el-button>
            </span>
         </template>
      </el-dialog>
      <!-- 渲染列表 -->
      <el-table :data="tableData" border style="width: 100%;margin-top: 20px;" id="table"
         :default-sort="{ prop: 'date', order: 'descending' }">
         <el-table-column prop="id" label="优惠券ID" align="center" sortable />
         <el-table-column prop="title" label="优惠券名称" align="center" width="100" />
         <el-table-column prop="type" label="优惠券类型" align="center" width="100">
            <template #default="scope">{{ scope.row.type == 1 ? '满减券' : '立减券' }}</template>
         </el-table-column>
         <el-table-column prop="description" label="介绍" align="center" />
         <el-table-column prop="total" label="优惠券数量" align="center" />
         <el-table-column prop="surplus" label="剩余数量" align="center" />
         <el-table-column prop="limit" label="每人限领" align="center" />
         <el-table-column prop="discount" label="满减金额" align="center">
            <template #default="scope">减免{{ scope.row.discount }}元</template>
         </el-table-column>
         <el-table-column prop="min" label="最低消费" align="center">
            <template #default="scope">满{{ scope.row.min }}可用</template>
         </el-table-column>
         <el-table-column prop="status" label="状态" align="center">
            <template #default="scope">
               <el-tag
                  :type="scope.row.gmtEnd < new Date().getTime() ? 'danger' : scope.row.status == 1 ? '' : 'danger'">{{ status(scope.row) }}</el-tag>
            </template>
         </el-table-column>
         <el-table-column prop="categoryTitle" label="使用类目名称" align="center">
            <template #default="scope">
               <div><el-tag>{{ scope.row.categoryTitle ? scope.row.categoryTitle : '全部类目' }}</el-tag></div>
            </template>
         </el-table-column>
         <el-table-column prop="categoryId" label="使用类目ID" align="center" />
         <el-table-column prop="days" label="领券相对天数" align="center">
            <template #default="scope">{{ scope.row.days ? scope.row.days : '无' }}</template>
         </el-table-column>
         <el-table-column prop="gmtStart" label="领券开始时间" align="center">
            <template #default="scope">{{ scope.row.gmtStart ? friendTimes(scope.row.gmtStart) : '无' }}</template>
         </el-table-column>
         <el-table-column prop="gmtEnd" label="领券结束时间" align="center">
            <template #default="scope">{{ scope.row.gmtEnd ? friendTimes(scope.row.gmtEnd) : '无' }}</template>
         </el-table-column>

         <el-table-column prop="" label="操作" align="center" width="150">
            <template #default="scope">
               <div>
                  <el-button size="small"
                     :type="scope.row.gmtEnd < new Date().getTime() ? 'primary' : scope.row.status == 1 ? 'danger' : 'primary'"
                     @click="handleSwitch(scope.$index, scope.row)">{{ buttonstatus(scope.row) }}</el-button>
                  <el-button size="small" type="info" @click="handlesee(scope.$index, scope.row)">查看</el-button>
               </div>
            </template>
         </el-table-column>
      </el-table>
      <Paging v-bind="pagination" @emitfather="CurrentList"></Paging>
   </div>
</template>
<script setup lang="ts">
import { Bottom, Plus, Search } from '@element-plus/icons-vue'//图标
import { get, post } from '@/utlis/http'
import { friendTimes } from '@/utlis/PackagingTime'//时间戳
import { ref, reactive, onMounted } from 'vue'
import Paging from '@/components/paging/Pagings.vue'//分页
import { ClassCoupon, classPagination } from '#/index'
import Files from 'file-saver'
import * as XLSX from 'xlsx'//表格格式
import { ElMessage, type FormInstance } from 'element-plus';
const pagination = reactive(new classPagination())//分页处理

let tableData = ref([])//接收渲染数据
const list = ref<Typeextensioncoupon>({//渲染数据
   _gp: 'admin.coupon',
   _mt: 'list',
   title: '',
   type: undefined,
   status: undefined,
   pageNo: 1,
   limit: 10
})
// 渲染并且将过期状态改成-1
function init() {
   get(list.value).then(res => {
      let { errno, errmsg, data } = res
      console.log(res);
      if (200 === errno) {
         tableData.value = data.items
         data.items.forEach((s: any) => {
            if (s.gmtEnd < new Date().getTime()) {
               s.status = -1
            }
         });
         pagination.total = data.total
      }

   })
}
onMounted(() => {
   init()
   category()
})

// 请求类目接口
let options = ref([])
function category() {
   let data = {
      _gp: 'admin.category',
      _mt: 'categoryTree'
   }
   get(data).then(res => {
      options.value = res.data
   })
}
/**
 * 继承数据
 */
class Classdataform extends ClassCoupon {
   /**
 * 有效期类型0相对天数，1指定时间
 */
   timeType = 1 | 0
   /**
 * 商品限制范围0全场通用1指定范围
 */
   goodsType = 0
}

// 渲染状态处理
function status(row: any) {//tag标签
   if (row.gmtEnd < new Date().getTime()) {
      return '已过期'
   } else if (row.status == 1) {
      return '正常'
   } else {
      return '下架'
   }
}
function buttonstatus(row: any) {//按钮
   return row.status == -1 ? '已过期' : row.status == 1 ? '冻结' : '激活'
}

// 点击切换状态
function handleSwitch(index: number, row: any) {
   let data = { _gp: 'admin.coupon', _mt: 'updateCouponStatus', id: row.id, status: row.status == 0 ? 1 : 0 }
   post(data).then(res => {
      init()
      if (row.status == 1) {
         ElMessage.success('已冻结')
      } else if (row.status == 0) {
         ElMessage.success("已激活")
      } else {
         ElMessage.error("无法更改状态")
      }
   })
}

// 查找
function handleSearch() {
   init()
}
// 查找前定义状态
const couponstatusMap = reactive([
   { value: 0, name: '下架' }, { value: 1, name: '正常' }, { value: -1, name: '已过期' }, { value: '', name: '全部' },
])
let dialogFormVisible = ref(false)
const ruleFormRef = ref<FormInstance>()
let formLabelWidth = '100px'
let form = ref({
   data: new Classdataform()
})
const rules = reactive({//弹出框的表单非空验证
   title: [{ required: true, message: '优惠券名称不能为空', trigger: 'blur' }],
   type: [{ required: true, message: '优惠券类型不能为空', trigger: 'blur' }],
   total: [{ required: true, message: '优惠数量不能为空', trigger: 'blur' },
   { pattern: /^([1-9]){0,3}$/, message: '请输入整数优惠数量不能少于1不能多于1000' }
   ],
   limit: [{ required: true, message: '每人限领不能为空', trigger: 'blur' },
   { pattern: /^([1-9]){0,2}$/, message: '请输入整数每人限领不能少于1不能超100次' }
   ],
   discount: [{ required: true, message: '不能为空', trigger: 'blur' },
   { pattern: /^([1-9]){0,4}$/, message: '请输入整数优惠金额不能少于1不能多于1万' }
   ],
   min: [{ required: true, message: '最低消费不能为空', trigger: 'blur' },
   { pattern: /^(\d){3,7}$/, message: '请输入整数最低消费不能少于100' }
   ],
   status: [{ required: true, message: '优惠状态不能为空', trigger: 'blur' }]
})
// 表单验证与添加编辑
function handleToggleConfirm(formEl: FormInstance | undefined) {
   if (!formEl) return
   formEl.validate((valid) => {
      if (valid) {
         let { days, total, limit, gmtStart, gmtEnd, timeType, goodsType, categoryId, discount, min } = form.value.data
         if (days == '' && (gmtStart == '' || gmtEnd == '')) {//相对天数与指定时间必填一个
            ElMessage.error('请填写优惠券使用区间')
            return
         }
         // 结束时间不能小于开始时间
         if (timeType === 0) {
            days = ''
            if (!gmtStart || !gmtEnd || gmtEnd < gmtStart) {
               ElMessage.error('请正确输入时间')
               return
            }
         } else {
            gmtStart = ''
            gmtEnd = ''
            if (days == '' || days == 0) {
               ElMessage.error('请正确填写时长，不能为空或者为0')
               return
            }
         }

         if (Number(discount) > Number(min)) {
            return ElMessage.error('优惠金额不能高于最低消费')
         }
         if (Number(limit) > Number(total)) {
            return ElMessage.error('优惠数量不能小于每人限购')
         }
         // 选择全场通用将类目清空
         if (goodsType === 0) {
            form.value.data.categoryId = ''
         }
         let data = {
            _gp: 'admin.coupon',
            _mt: 'create',
            ...form.value.data
         }
         post(data).then(res => {
            let { errno, errmsg } = res
            if (200 == errno) {
               dialogFormVisible.value = false
               init()
               ElMessage.success(errmsg)
            } else {
               ElMessage.error(errmsg)
            }
         })
      } else {
         return false
      }
   })

}
// 添加弹出框
function add() {
   bool.value = false
   dialogFormVisible.value = true
   form.value.data = new Classdataform()
}
// 查看
let bool = ref(false)
function handlesee(index: number, row: ClassCoupon) {
   Object.assign(form.value.data, row)
   if (row.days) {//相对天数有显示没有显示时间
      form.value.data.timeType = 1
   } else {
      form.value.data.timeType = 0
   }
   if (row.categoryId) {//有分类显示分类
      form.value.data.goodsType = 1
   }
   dialogFormVisible.value = true
   bool.value = true//查看变禁用
   return row.status == -1 ? form.value.data.status = '已过期' : row.status == 1 ? '正常' : '下架'//根据状态返回文字

}
// 分页
function CurrentList(v: classPagination) {
   list.value.pageNo = v.pageNo
   list.value.limit = v.pageSize
   init()
}

function exports() {//点击事件
   let xlsxparam = { raw: true }//转换成excel时，使用原始的格式raw：表示导出数据是否是未加工的
   let wb = XLSX.utils.table_to_book(document.querySelector("#table"), xlsxparam)//获得表格的id
   const wbout = XLSX.write(wb, {//保存格式第一个参数wb就是内容，第二个是文件的相关配置
      bookType: 'xlsx',
      bookSST: true,
      type: 'array'
   })
   try {//Files代表浏览器插件通过Blob来传入上面的内容和配置最后调用saveAs来保存文件，第一个参数blob对象，第二个是文件名
      Files.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'file-name.xlsx')
   } catch (e) {
      if (typeof console !== 'undefined') console.log(e, wbout)
   }
}
</script>
<style scoped>
.input-length {
   width: 200px;
   margin-right: 10px;
}
</style>